package com.muyu.cloud.auth.service.impl;

import com.muyu.cloud.auth.domain.response.TokenRes;
import com.muyu.cloud.auth.service.AuthService;
import com.muyu.cloud.system.domain.UserInfo;
import com.muyu.cloud.system.remote.RemoteUserInfoService;
import com.muyu.common.constant.Constants;
import com.muyu.common.constant.JwtConstants;
import com.muyu.common.constant.TokenConstants;
import com.muyu.common.redis.service.RedisService;
import com.muyu.common.result.Result;
import com.muyu.common.utils.JwtUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @Author: DongZeLiang
 * @date: 2024/5/24
 * @Description: 用户实现类
 * @Version: 1.0
 */
@Log4j2
@Service
@AllArgsConstructor
public class AuthServiceImpl implements AuthService {


    private final RemoteUserInfoService remoteUserInfoService;

    private final RedisService redisService;

    /**
     * 通过用户名和密码获取到用户信息
     *
     * @param userName 用户名称
     * @param password 用户密码
     *
     * @return 登录信息
     */
    @Override
    public UserInfo login (String userName, String password) {
        Result<UserInfo> userInfoResult = remoteUserInfoService.findByuserName(userName);

        if (userInfoResult.getCode() == Constants.ERROR){
            log.info("用户登录失败：{}", userInfoResult.getMsg());
            throw new RuntimeException(
                    String.format("用户登录失败：[%s]", userInfoResult.getMsg())
            );
        }
        UserInfo userInfo = userInfoResult.getData();
        if (userInfo == null){
            log.info("用户登录失败：{}", userInfoResult.getMsg());
            throw new RuntimeException("用户登录失败：[用户名或者密码不存在]");
        }

        if (!password.equals(userInfo.getPassword())){
            log.info("用户登录失败：密码错误");
            throw new RuntimeException("用户登录失败：[用户名或者密码不存在]");
        }

        return userInfo;
    }

    /**
     * 通过登录用户信息，生成token
     *
     * @param userLoginInfo 用户信息
     *
     * @return token
     */
    @Override
    public TokenRes genToken (UserInfo userLoginInfo) {

        String userKey = UUID.randomUUID().toString().replace("-", "");

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(JwtConstants.DETAILS_USER_ID, userLoginInfo.getId());
        dataMap.put(JwtConstants.DETAILS_userName, userLoginInfo.getUserName());
        dataMap.put(JwtConstants.USER_KEY, userKey);
        String token = JwtUtils.createToken(dataMap);

        redisService.setCacheObject(
                TokenConstants.LOGIN_TOKEN_KEY + userKey,
                userLoginInfo,
                TokenConstants.EXPIRATION,
                TimeUnit.MINUTES
        );

        return TokenRes.builder()
                .token(token)
                .expiresIn(TokenConstants.EXPIRATION)
                .build();
    }

    /**
     * 根据token获取用户相信信息
     *
     * @param userKey token
     *
     * @return 用户信息
     */
    @Override
    public UserInfo loginInfo (String userKey) {
        return redisService.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }

    /**
     * 退出登录
     *
     * @param userKey 令牌
     */
    @Override
    public void loginOut (String userKey) {
        redisService.deleteObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
